package com.tjhk.demo.config;

import com.tjhk.demo.contants.RabbitMqExchangeConstants;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class RabbitMqConfig {

    @Autowired
    private CachingConnectionFactory connectionFactory;

    //队列声明交换机
    @Bean(RabbitMqExchangeConstants.TOPIC_EXCHANGE_NAME)
    public Exchange topExchange(){
        return ExchangeBuilder.topicExchange(RabbitMqExchangeConstants.TOPIC_EXCHANGE_NAME).durable(true).build();
    }
    @Bean(RabbitMqExchangeConstants.DIRECT_EXCHANGE_NAME)
    public Exchange directExchange(){
        return ExchangeBuilder.directExchange(RabbitMqExchangeConstants.DIRECT_EXCHANGE_NAME).durable(true).build();
    }
    @Bean(RabbitMqExchangeConstants.FANOUT_EXCHANGE_NAME)
    public Exchange fanoutExchange(){
        return ExchangeBuilder.fanoutExchange(RabbitMqExchangeConstants.FANOUT_EXCHANGE_NAME).durable(true).build();
    }
    /**
     * 如果需要在生产者需要消息发送后的回调，
     * 需要对rabbitTemplate设置ConfirmCallback对象，
     * 由于不同的生产者需要对应不同的ConfirmCallback，
     * 如果rabbitTemplate设置为单例bean，
     * 则所有的rabbitTemplate实际的ConfirmCallback为最后一次申明的ConfirmCallback。
     * @return
     */
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        return template;
    }
}
